package com.atguigu.yygh.gateway.config;

import com.atguigu.yygh.common.utils.JwtHelper;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 创建自定义过滤器
 */
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    //这个是spring带的一个工具类，可以判断来匹配路径
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 自定义过滤器的执行方法
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取request对象
        ServerHttpRequest request = exchange.getRequest();

        //获取请求路径
        String path = request.getURI().getPath();
        //判断进来的请求路径是否为需要登录的路径，不是所有的路径都需要登录
        if (antPathMatcher.match("/api/order/**",path)){
            //获取token
            List<String> list = request.getHeaders().get("token");
            //判断是否有token，
            if (list == null){
                ServerHttpResponse response = exchange.getResponse();
                return out(response);
            } else {
                //判断token是否过了有效时间
                if (JwtHelper.isExpiration(list.get(0))){
                    ServerHttpResponse response = exchange.getResponse();
                    return out(response);
                }
            }
        }
        //放行
        return chain.filter(exchange);
    }

    /**
     * 这个是优先级，这个方法来自ordered，0表示优先级最高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }

    //返回信息
    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", false);
        message.addProperty("code", 28004);
        message.addProperty("data", "鉴权失败");
        byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bits);
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }
}
